<template>
  <el-dialog
    :model-value="visible"
    title="配送位置"
    width="90%"
    :close-on-click-modal="false"
    @close="handleClose"
    class="delivery-map-dialog"
  >
    <div class="map-container">
      <!-- 地图头部信息 -->
      <div class="map-header">
        <div class="order-info">
          <h3>订单 #{{ order?.id }}</h3>
          <div class="location-item pickup-location">
            <el-icon><Shop /></el-icon>
            <span class="location-label">取餐:</span>
            <span>{{ order?.pickupAddress || order?.storeAddress || '商家地址' }}</span>
          </div>
          <div class="location-item delivery-location">
            <el-icon><Location /></el-icon>
            <span class="location-label">送达:</span>
            <span>{{ order?.delivery_address }}</span>
          </div>
          <p class="phone-info">
            <el-icon><Phone /></el-icon>
            {{ order?.customer_phone }}
          </p>
        </div>
        <div class="distance-info">
          <el-tag :type="getDistanceTagType()" size="large">
            {{ getDistanceText() }}
          </el-tag>
          <el-tag type="info" size="large" class="eta-tag">
            {{ getTimeText() }}
          </el-tag>
          <el-tag 
            v-if="getRouteDescription()" 
            type="warning" 
            size="small" 
            class="route-description"
          >
            {{ getRouteDescription() }}
          </el-tag>
        </div>
      </div>

      <!-- 地图区域 -->
      <div :id="mapId" class="map-area" ref="mapContainer">
        <div class="map-loading" v-show="mapLoading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>正在加载地图...</p>
        </div>
      </div>

      <!-- 地图底部操作栏 -->
      <div class="map-actions">
        <el-button 
          type="primary" 
          @click="centerToRider"
          :icon="Location"
        >
          我的位置
        </el-button>
        <el-button 
          type="success" 
          @click="centerToDestination"
          :icon="Place"
        >
          配送地址
        </el-button>
        <!-- <el-button 
          type="warning" 
          @click="showRoute"
          :icon="Guide"
        >
          规划路线
        </el-button> -->
        <el-button 
          type="info" 
          @click="openNavigation"
          :icon="Position"
        >
          导航
        </el-button>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button 
          type="primary" 
          @click="updateLocation"
          :loading="locationUpdating"
        >
          更新我的位置
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Location, Phone, Loading, Place, Guide, Position, Shop } from '@element-plus/icons-vue'

// 高德地图类型声明
declare global {
  interface Window {
    AMap: any
  }
}

// 组件Props
interface Props {
  visible: boolean
  order: any
  riderLocation?: {
    latitude: number
    longitude: number
  }
}

const props = defineProps<Props>()
const emit = defineEmits<{
  close: []
  locationUpdate: [location: { latitude: number; longitude: number }]
}>()

// 状态管理
const mapContainer = ref<HTMLElement>()
const mapLoading = ref(true)
const locationUpdating = ref(false)
const distance = ref(0)
const estimatedTime = ref(0)
const mapId = ref(`delivery-map-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`)

// 地图相关变量
let map: any = null
let riderMarker: any = null
let destinationMarker: any = null
let pickupMarker: any = null
let routeLine: any = null

// 监听弹窗显示状态
watch(() => props.visible, async (newVal) => {
  if (newVal) {
    // 等待DOM完全更新
    await nextTick()
    // 再等待一个微任务以确保DOM完全渲染
    await new Promise(resolve => setTimeout(resolve, 0))
    initMap()
  } else {
    destroyMap()
  }
})

// 初始化地图
const initMap = async () => {
  try {
    mapLoading.value = true
    
    // 等待多个周期确保DOM完全准备好
    await nextTick()
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 多次检查DOM容器是否存在
    let retryCount = 0
    const maxRetries = 5
    
    while (retryCount < maxRetries) {
      if (mapContainer.value && document.getElementById(mapId.value)) {
        break
      }
      await new Promise(resolve => setTimeout(resolve, 50))
      retryCount++
    }
    
    if (!mapContainer.value || !document.getElementById(mapId.value)) {
      console.warn('地图容器在多次尝试后仍不存在，容器:', mapContainer.value, 'DOM ID:', mapId.value)
      return
    }
    
    // 检查是否有高德地图API（或开发模式）
    const isDevelopmentMode = import.meta.env.DEV && !import.meta.env.VITE_DISABLE_MAP_DEV_MODE
    
    if (typeof window.AMap !== 'undefined' || isDevelopmentMode) {
      // 使用真实的高德地图API或开发模式
      await initAMapInstance()
    } else {
      // 降级到简单地图显示
      await initSimpleMap()
    }
    
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图加载失败')
    await initSimpleMap() // 降级处理
  } finally {
    mapLoading.value = false
  }
}

// 初始化高德地图实例
const initAMapInstance = async () => {
  // 确定地图中心点（优先使用骑手位置，其次是配送地址）
  let centerLocation = [116.4074, 39.9042] // 默认北京中心
  
  if (props.riderLocation) {
    centerLocation = [props.riderLocation.longitude, props.riderLocation.latitude]
  } else if (props.order?.delivery_coordinates) {
    const [lat, lng] = props.order.delivery_coordinates.split(',').map(Number)
    centerLocation = [lng, lat]
  }

  // 创建地图实例
  map = new window.AMap.Map(mapId.value, {
    zoom: 15,
    center: centerLocation,
    resizeEnable: true,
    rotateEnable: false,
    pitchEnable: false,
    mapStyle: 'amap://styles/normal',
    viewMode: '2D'
  })

  // 等待地图加载完成
  await new Promise((resolve) => {
    map.on('complete', resolve)
  })

  // 添加骑手标记
  if (props.riderLocation) {
    addRiderMarker(props.riderLocation)
  }

  // 添加商家标记
  if (props.order?.pickup_coordinates) {
    addPickupMarker(props.order.pickup_coordinates)
  }

  // 添加目的地标记
  if (props.order?.delivery_coordinates) {
    addDestinationMarker(props.order.delivery_coordinates)
  }

  // 计算距离和时间
  calculateDistanceAndTime()
  
  // 自适应显示所有标记
  setTimeout(() => {
    const markers = [riderMarker, pickupMarker, destinationMarker].filter(Boolean)
    if (markers.length > 0) {
      map.setFitView(markers, false, [50, 50, 50, 50])
    }
  }, 500)
}

// 初始化简单地图显示
const initSimpleMap = async () => {
  const mapDiv = mapContainer.value
  if (!mapDiv) return
  
  // 清空容器
  mapDiv.innerHTML = ''
  
  // 创建简单的地图显示
  const mapContent = document.createElement('div')
  mapContent.className = 'simple-map'
  mapContent.innerHTML = `
    <div class="map-info">
      <h3>配送地图</h3>
      <div class="location-items">
        <div class="location-item rider">
          <div class="marker-icon rider-marker">🚴</div>
          <div class="location-details">
            <p><strong>骑手位置</strong></p>
            <p>纬度: ${props.riderLocation?.latitude || '39.9042'}</p>
            <p>经度: ${props.riderLocation?.longitude || '116.4074'}</p>
          </div>
        </div>
        <div class="location-item destination">
          <div class="marker-icon destination-marker">📍</div>
          <div class="location-details">
            <p><strong>配送地址</strong></p>
            <p>${props.order?.delivery_address || '配送地址'}</p>
            ${props.order?.delivery_coordinates ? `
              <p>坐标: ${props.order.delivery_coordinates}</p>
            ` : ''}
          </div>
        </div>
      </div>
      <div class="map-note">
        <p>💡 提示：安装高德地图API可显示完整地图</p>
      </div>
    </div>
  `
  
  mapDiv.appendChild(mapContent)
  
  // 模拟距离计算
  simulateMapData()
}

// 添加骑手标记
const addRiderMarker = (location: { latitude: number; longitude: number }) => {
  if (!map) return

  const position = new window.AMap.LngLat(location.longitude, location.latitude)
  
  // 创建自定义图标
  const riderIcon = new window.AMap.Icon({
    image: 'data:image/svg+xml;base64,' + btoa(`
      <svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
        <circle cx="20" cy="20" r="18" fill="#1890ff" stroke="#fff" stroke-width="3"/>
        <circle cx="20" cy="20" r="12" fill="#0050b3"/>
        <path d="M12 18 L20 12 L28 18 L24 22 L20 20 L16 22 Z" fill="white"/>
        <circle cx="15" cy="25" r="3" fill="white"/>
        <circle cx="25" cy="25" r="3" fill="white"/>
      </svg>
    `),
    size: new window.AMap.Size(40, 40),
    imageSize: new window.AMap.Size(40, 40)
  })
  
  riderMarker = new window.AMap.Marker({
    position: position,
    title: '骑手位置',
    icon: riderIcon,
    anchor: 'center',
    zIndex: 100
  })

  map.add(riderMarker)
  
  // 添加信息窗口
  const infoWindow = new window.AMap.InfoWindow({
    content: `
      <div style="padding: 10px;">
        <h4 style="margin: 0 0 8px 0; color: #1890ff;">🚴 骑手位置</h4>
        <p style="margin: 0; font-size: 12px;">
          经度: ${location.longitude.toFixed(6)}<br>
          纬度: ${location.latitude.toFixed(6)}
        </p>
      </div>
    `,
    offset: new window.AMap.Pixel(0, -40)
  })
  
  riderMarker.on('click', () => {
    infoWindow.open(map, position)
  })
  
  console.log('骑手标记已添加:', position.toString())
}

// 添加商家标记
const addPickupMarker = (coordinates: string) => {
  if (!map) return

  try {
    // 解析坐标字符串 "latitude,longitude"
    const [lat, lng] = coordinates.split(',').map(Number)
    const position = new window.AMap.LngLat(lng, lat)

    // 创建自定义图标
    const pickupIcon = new window.AMap.Icon({
      image: 'data:image/svg+xml;base64,' + btoa(`
        <svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
          <circle cx="20" cy="20" r="18" fill="#52c41a" stroke="#fff" stroke-width="3"/>
          <circle cx="20" cy="20" r="12" fill="#389e0d"/>
          <rect x="12" y="14" width="16" height="12" rx="2" fill="white"/>
          <rect x="14" y="16" width="4" height="2" fill="#389e0d"/>
          <rect x="22" y="16" width="4" height="2" fill="#389e0d"/>
          <rect x="14" y="20" width="12" height="1" fill="#389e0d"/>
          <rect x="14" y="22" width="8" height="1" fill="#389e0d"/>
        </svg>
      `),
      size: new window.AMap.Size(40, 40),
      imageSize: new window.AMap.Size(40, 40)
    })

    pickupMarker = new window.AMap.Marker({
      position: position,
      title: '取餐地址',
      icon: pickupIcon,
      anchor: 'center',
      zIndex: 100
    })

    map.add(pickupMarker)
    
    // 添加信息窗口
    const infoWindow = new window.AMap.InfoWindow({
      content: `
        <div style="padding: 10px; max-width: 200px;">
          <h4 style="margin: 0 0 8px 0; color: #52c41a;">🏪 取餐地址</h4>
          <p style="margin: 0 0 8px 0; font-size: 12px;">
            ${props.order?.pickupAddress || props.order?.storeAddress || '商家地址'}
          </p>
          <p style="margin: 0; font-size: 11px; color: #666;">
            经度: ${lng.toFixed(6)}<br>
            纬度: ${lat.toFixed(6)}
          </p>
        </div>
      `,
      offset: new window.AMap.Pixel(0, -40)
    })
    
    pickupMarker.on('click', () => {
      infoWindow.open(map, position)
    })
    
    console.log('取餐地标记已添加:', position.toString())
  } catch (error) {
    console.error('取餐地坐标解析失败:', error, coordinates)
  }
}

// 添加目的地标记
const addDestinationMarker = (coordinates: string) => {
  if (!map) return

  try {
    // 解析坐标字符串 "latitude,longitude"
    const [lat, lng] = coordinates.split(',').map(Number)
    const position = new window.AMap.LngLat(lng, lat)

    // 创建自定义图标
    const destIcon = new window.AMap.Icon({
      image: 'data:image/svg+xml;base64,' + btoa(`
        <svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
          <circle cx="20" cy="20" r="18" fill="#f5222d" stroke="#fff" stroke-width="3"/>
          <circle cx="20" cy="20" r="12" fill="#cf1322"/>
          <path d="M20 8 L26 16 L22 16 L22 24 L18 24 L18 16 L14 16 Z" fill="white"/>
          <circle cx="20" cy="28" r="2" fill="white"/>
        </svg>
      `),
      size: new window.AMap.Size(40, 40),
      imageSize: new window.AMap.Size(40, 40)
    })

    destinationMarker = new window.AMap.Marker({
      position: position,
      title: '配送地址',
      icon: destIcon,
      anchor: 'center',
      zIndex: 100
    })

    map.add(destinationMarker)
    
    // 添加信息窗口
    const infoWindow = new window.AMap.InfoWindow({
      content: `
        <div style="padding: 10px; max-width: 200px;">
          <h4 style="margin: 0 0 8px 0; color: #f5222d;">📍 配送地址</h4>
          <p style="margin: 0 0 8px 0; font-size: 12px;">
            ${props.order?.delivery_address || '配送地址'}
          </p>
          <p style="margin: 0; font-size: 11px; color: #666;">
            经度: ${lng.toFixed(6)}<br>
            纬度: ${lat.toFixed(6)}
          </p>
        </div>
      `,
      offset: new window.AMap.Pixel(0, -40)
    })
    
    destinationMarker.on('click', () => {
      infoWindow.open(map, position)
    })
    
    console.log('目的地标记已添加:', position.toString())
  } catch (error) {
    console.error('目的地坐标解析失败:', error, coordinates)
  }
}

// 智能计算距离和时间（根据订单状态）
const calculateDistanceAndTime = () => {
  if (!props.riderLocation) {
    simulateMapData()
    return
  }

  try {
    const orderStatus = props.order?.status
    const hasPickupCoords = props.order?.pickup_coordinates
    const hasDeliveryCoords = props.order?.delivery_coordinates

    // 根据订单状态决定计算路径
    if (shouldCalculateDirectRoute(orderStatus)) {
      // 已取餐：直接计算骑手到顾客的距离
      calculateDirectRoute()
    } else {
      // 未取餐：计算骑手→商家→顾客的总路径
      calculateFullRoute()
    }
  } catch (error) {
    console.error('距离计算失败:', error)
    simulateMapData()
  }
}

// 判断是否应该计算直接路径（已取餐状态）
const shouldCalculateDirectRoute = (status?: string) => {
  const pickedUpStatuses = [
    'FOOD_PICKED',    // 已取餐
    'PICKED_UP',      // 兼容旧状态
    'DELIVERING',     // 配送中
    'DELIVERED',      // 已送达
    'COMPLETED'       // 已完成
  ]
  return pickedUpStatuses.includes(status || '')
}

// 计算直接路径（骑手→顾客）
const calculateDirectRoute = () => {
  if (!props.order?.delivery_coordinates) {
    simulateMapData()
    return
  }

  const [destLat, destLng] = props.order.delivery_coordinates.split(',').map(Number)
  
  if (typeof window.AMap !== 'undefined') {
    const riderPos = new window.AMap.LngLat(props.riderLocation!.longitude, props.riderLocation!.latitude)
    const destPos = new window.AMap.LngLat(destLng, destLat)
    
    distance.value = riderPos.distance(destPos) / 1000 // 转换为公里
    estimatedTime.value = Math.ceil(distance.value * 2.5) // 配送中速度稍快，每公里2.5分钟
  } else {
    // 简单的距离计算
    distance.value = calculateHaversineDistance(
      props.riderLocation!.latitude, 
      props.riderLocation!.longitude,
      destLat, 
      destLng
    )
    estimatedTime.value = Math.ceil(distance.value * 2.5)
  }
  
  console.log(`直接路径计算完成: ${distance.value.toFixed(2)}km, ${estimatedTime.value}分钟`)
}

// 计算完整路径（骑手→商家→顾客）
const calculateFullRoute = () => {
  if (!props.order?.pickup_coordinates || !props.order?.delivery_coordinates) {
    simulateMapData()
    return
  }

  const [pickupLat, pickupLng] = props.order.pickup_coordinates.split(',').map(Number)
  const [destLat, destLng] = props.order.delivery_coordinates.split(',').map(Number)
  
  if (typeof window.AMap !== 'undefined') {
    const riderPos = new window.AMap.LngLat(props.riderLocation!.longitude, props.riderLocation!.latitude)
    const pickupPos = new window.AMap.LngLat(pickupLng, pickupLat)
    const destPos = new window.AMap.LngLat(destLng, destLat)
    
    // 计算两段距离：骑手→商家 + 商家→顾客
    const distanceToPickup = riderPos.distance(pickupPos) / 1000
    const distanceToDestination = pickupPos.distance(destPos) / 1000
    
    distance.value = distanceToPickup + distanceToDestination
    // 考虑取餐等待时间（5分钟）+ 路程时间
    estimatedTime.value = Math.ceil(distanceToPickup * 3) + Math.ceil(distanceToDestination * 2.5) + 5
  } else {
    // 简单计算
    const distanceToPickup = calculateHaversineDistance(
      props.riderLocation!.latitude, 
      props.riderLocation!.longitude,
      pickupLat, 
      pickupLng
    )
    const distanceToDestination = calculateHaversineDistance(
      pickupLat, 
      pickupLng,
      destLat, 
      destLng
    )
    
    distance.value = distanceToPickup + distanceToDestination
    estimatedTime.value = Math.ceil(distanceToPickup * 3) + Math.ceil(distanceToDestination * 2.5) + 5
  }
  
  console.log(`完整路径计算完成: ${distance.value.toFixed(2)}km, ${estimatedTime.value}分钟 (含取餐等待)`)
}

// Haversine距离计算公式
const calculateHaversineDistance = (lat1: number, lng1: number, lat2: number, lng2: number) => {
  const R = 6371 // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180
  const dLng = (lng2 - lng1) * Math.PI / 180
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
            Math.cos(lat1 * Math.PI / 180) * 
            Math.cos(lat2 * Math.PI / 180) * 
            Math.sin(dLng/2) * Math.sin(dLng/2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  return R * c
}

// 逆地理编码：将坐标转换为地址
const reverseGeocode = async (lat: number, lng: number): Promise<string> => {
  // 检查API配置
  const apiKey = import.meta.env.VITE_AMAP_KEY || '52dd86f4793513b166a46cb375010201'
  if (!apiKey || apiKey === 'YOUR_AMAP_KEY') {
    throw new Error('高德地图API Key未配置')
  }
  
  try {
    const response = await fetch(
      `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${apiKey}&radius=1000&extensions=base`
    )
    const data = await response.json()
    
    if (data.status === '1' && data.regeocode) {
      const regeocode = data.regeocode
      // 优先使用具体地址，如果没有则使用行政区域
      const address = regeocode.formatted_address || 
                     (regeocode.addressComponent?.township + regeocode.addressComponent?.street) ||
                     '当前位置'
      
      console.log('逆地理编码成功:', { lat, lng, address })
      return address
    } else {
      throw new Error(`逆地理编码失败: ${data.info}`)
    }
  } catch (error) {
    console.error('逆地理编码API调用失败:', error)
    throw error
  }
}

// 模拟地图数据（用于演示）
const simulateMapData = () => {
  distance.value = Math.random() * 5 + 1 // 1-6公里
  estimatedTime.value = Math.ceil(distance.value * 3) // 假设每公里3分钟
}

// 格式化距离显示
const formatDistance = (dist: number) => {
  if (dist < 1) {
    return `${Math.round(dist * 1000)}m`
  } else {
    return `${dist.toFixed(1)}km`
  }
}

// 获取距离文本（根据状态显示）
const getDistanceText = () => {
  const isDirectRoute = shouldCalculateDirectRoute(props.order?.status)
  const prefix = isDirectRoute ? '剩余距离' : '总距离'
  return `${prefix}: ${formatDistance(distance.value)}`
}

// 获取时间文本（根据状态显示）
const getTimeText = () => {
  const isDirectRoute = shouldCalculateDirectRoute(props.order?.status)
  if (isDirectRoute) {
    return `预计送达: ${estimatedTime.value}分钟`
  } else {
    return `预计完成: ${estimatedTime.value}分钟`
  }
}

// 获取路径描述
const getRouteDescription = () => {
  const isDirectRoute = shouldCalculateDirectRoute(props.order?.status)
  if (isDirectRoute) {
    return '直达顾客'
  } else {
    return '经商家取餐'
  }
}

// 获取距离标签类型
const getDistanceTagType = () => {
  if (distance.value < 1) return 'success'
  if (distance.value < 3) return 'warning'
  return 'danger'
}

// 定位到骑手位置
const centerToRider = () => {
  if (map && riderMarker) {
    map.setCenter(riderMarker.getPosition())
    map.setZoom(16)
    ElMessage.success('已定位到骑手位置')
  } else {
    ElMessage.info(`骑手位置: ${props.riderLocation?.latitude || '39.9042'}, ${props.riderLocation?.longitude || '116.4074'}`)
  }
}

// 定位到目的地
const centerToDestination = () => {
  if (map && destinationMarker) {
    map.setCenter(destinationMarker.getPosition())
    map.setZoom(16)
    ElMessage.success('已定位到配送地址')
  } else {
    ElMessage.info(`配送地址: ${props.order?.delivery_address || '配送地址'}`)
  }
}

// 检查高德地图API是否完全加载
const isAMapReady = () => {
  return typeof window.AMap !== 'undefined' && 
         window.AMap.DrivingPolicy && 
         window.AMap.Driving &&
         map
}

// 智能路线规划（根据订单状态）
const showRoute = () => {
  if (!props.riderLocation) {
    ElMessage.warning('骑手位置信息缺失，无法规划路线')
    return
  }

  // 检查高德地图API是否完全加载
  if (!isAMapReady()) {
    ElMessage.error('地图API未完全加载，请稍后再试')
    return
  }

  try {
    const orderStatus = props.order?.status
    const isPickedUp = shouldCalculateDirectRoute(orderStatus)
    
    if (isPickedUp) {
      // 已取餐：规划直接路线（骑手→顾客）
      planDirectRoute()
    } else {
      // 未取餐：规划完整路线（骑手→商家→顾客）
      planFullRoute()
    }
  } catch (error) {
    console.error('路线规划失败:', error)
    ElMessage.error('路线规划失败')
  }
}

// 规划直接路线（骑手→顾客）
const planDirectRoute = () => {
  if (!props.order?.delivery_coordinates || !destinationMarker) {
    ElMessage.warning('配送地址信息缺失，无法规划路线')
    return
  }

  if (isAMapReady()) {
    // 清除现有路线
    clearExistingRoutes()

    const driving = new window.AMap.Driving({
      map: map,
      panel: null,
      policy: window.AMap.DrivingPolicy.LEAST_TIME // 最短时间策略
    })

    driving.search(
      riderMarker.getPosition(),
      destinationMarker.getPosition(),
      (status: string, result: any) => {
        if (status === 'complete') {
          ElMessage.success('直达路线规划成功')
          // 自适应显示路线
          setTimeout(() => {
            map.setFitView([riderMarker, destinationMarker], false, [50, 50, 50, 50])
          }, 500)
        } else {
          ElMessage.error('路线规划失败')
        }
      }
    )
  } else {
    // API未完全加载时的降级处理
    ElMessage.warning('地图API未完全加载，显示简化路线信息')
    ElMessage.success(`直达路线：骑手位置 → ${props.order?.delivery_address || '配送地址'}`)
  }
}

// 规划完整路线（骑手→商家→顾客）
const planFullRoute = () => {
  if (!props.order?.pickup_coordinates || !props.order?.delivery_coordinates || 
      !pickupMarker || !destinationMarker) {
    ElMessage.warning('地址信息不完整，无法规划完整路线')
    return
  }

  if (isAMapReady()) {
    // 清除现有路线
    clearExistingRoutes()

    // 第一段路线：骑手→商家
    const driving1 = new window.AMap.Driving({
      map: map,
      panel: null,
      policy: window.AMap.DrivingPolicy.LEAST_TIME,
      strokeColor: '#1890ff', // 蓝色路线
      strokeWeight: 5
    })

    // 第二段路线：商家→顾客
    const driving2 = new window.AMap.Driving({
      map: map,
      panel: null,
      policy: window.AMap.DrivingPolicy.LEAST_TIME,
      strokeColor: '#52c41a', // 绿色路线
      strokeWeight: 5
    })

    let routesCompleted = 0
    const totalRoutes = 2

    // 规划第一段路线
    driving1.search(
      riderMarker.getPosition(),
      pickupMarker.getPosition(),
      (status: string, result: any) => {
        routesCompleted++
        if (status === 'complete') {
          console.log('第一段路线规划成功：骑手→商家')
          checkRoutesCompletion()
        } else {
          ElMessage.error('到商家的路线规划失败')
        }
      }
    )

    // 规划第二段路线
    driving2.search(
      pickupMarker.getPosition(),
      destinationMarker.getPosition(),
      (status: string, result: any) => {
        routesCompleted++
        if (status === 'complete') {
          console.log('第二段路线规划成功：商家→顾客')
          checkRoutesCompletion()
        } else {
          ElMessage.error('到顾客的路线规划失败')
        }
      }
    )

    // 检查所有路线是否完成
    const checkRoutesCompletion = () => {
      if (routesCompleted === totalRoutes) {
        ElMessage.success('完整配送路线规划成功')
        // 自适应显示所有标记和路线
        setTimeout(() => {
          const allMarkers = [riderMarker, pickupMarker, destinationMarker].filter(Boolean)
          map.setFitView(allMarkers, false, [50, 50, 50, 50])
        }, 500)
      }
    }
  } else {
    // API未完全加载时的降级处理
    ElMessage.warning('地图API未完全加载，显示简化路线信息')
    ElMessage.success(`完整路线：骑手 → ${props.order?.pickupAddress || '商家'} → ${props.order?.delivery_address || '配送地址'}`)
  }
}

// 清除现有路线
const clearExistingRoutes = () => {
  if (map && routeLine) {
    map.remove(routeLine)
    routeLine = null
  }
  // 清除可能存在的多条路线
  if (map && typeof window.AMap !== 'undefined') {
    map.clearMap()
    // 重新添加标记
    if (riderMarker) map.add(riderMarker)
    if (pickupMarker) map.add(pickupMarker)
    if (destinationMarker) map.add(destinationMarker)
  }
}

// 打开导航
// 智能导航（根据订单状态）
const openNavigation = () => {
  try {
    const orderStatus = props.order?.status
    const isPickedUp = shouldCalculateDirectRoute(orderStatus)
    
    if (isPickedUp) {
      // 已取餐：直接导航到顾客地址
      navigateToDestination()
    } else {
      // 未取餐：导航到商家，并设置顾客地址作为途径点
      navigateWithWaypoints()
    }
  } catch (error) {
    console.error('导航启动失败:', error)
    ElMessage.error('导航启动失败')
  }
}

// 带途径点的完整导航（未取餐状态使用）
const navigateWithWaypoints = async () => {
  if (!props.order?.pickup_coordinates || !props.order?.delivery_coordinates) {
    ElMessage.warning('地址信息不完整，无法启动完整导航')
    // 降级到单点导航
    navigateToPickup()
    return
  }

  try {
    const [pickupLat, pickupLng] = props.order.pickup_coordinates.split(',').map(Number)
    const [destLat, destLng] = props.order.delivery_coordinates.split(',').map(Number)
    
    const pickupAddress = props.order.pickupAddress || props.order.storeAddress || '商家地址'
    const destAddress = props.order.delivery_address || props.order.address || '配送地址'
    
    // 获取骑手当前位置的地址
    let riderAddress = '我的位置'
    if (props.riderLocation) {
      try {
        riderAddress = await reverseGeocode(props.riderLocation.latitude, props.riderLocation.longitude)
      } catch (error) {
        console.warn('逆地理编码失败，使用默认起点名称:', error)
        riderAddress = '当前位置'
      }
    }
    
    console.log('导航信息:', {
      rider: { lat: props.riderLocation?.latitude, lng: props.riderLocation?.longitude, address: riderAddress },
      pickup: { lat: pickupLat, lng: pickupLng, address: pickupAddress },
      destination: { lat: destLat, lng: destLng, address: destAddress }
    })
    
    // 移动端：尝试调用高德地图APP的途径点导航
    if (/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
      // 方案1：高德APP途径点导航URL - 使用mid参数设置途径点
      const amapUrl = `androidamap://route?` +
        `sourceApplication=外卖骑手&` +
        `dlat=${destLat}&dlon=${destLng}&dname=${encodeURIComponent(destAddress)}&` +
        `mid=${pickupLng},${pickupLat}&` +
        `mname=${encodeURIComponent(pickupAddress)}&` +
        `dev=0&t=0`
      
      console.log('APP导航URL:', amapUrl)
      
      try {
        window.location.href = amapUrl
        ElMessage.success(`正在启动高德地图APP完整导航：${riderAddress} → ${pickupAddress} → ${destAddress}`)
      } catch (error) {
        // APP调用失败，降级到网页版
        navigateWithWebFallback(pickupLat, pickupLng, destLat, destLng, pickupAddress, destAddress, riderAddress)
      }
    } else {
      // 桌面端：使用网页版途径点导航
      navigateWithWebFallback(pickupLat, pickupLng, destLat, destLng, pickupAddress, destAddress, riderAddress)
    }
  } catch (error) {
    console.error('完整导航启动失败:', error)
    ElMessage.error('完整导航启动失败，切换到简单导航')
    navigateToPickup()
  }
}

// 网页版途径点导航（降级方案）
const navigateWithWebFallback = (pickupLat: number, pickupLng: number, destLat: number, destLng: number, pickupAddress: string, destAddress: string, riderAddress: string = '我的位置') => {
  // 方案1：使用高德地图网页版的正确途径点格式
  try {
    // 构建标准的高德地图网页版URL，参考官方格式
    // 如果有骑手位置，使用具体坐标和地址
    let fromParams = `from[name]=${encodeURIComponent(riderAddress)}`
    if (props.riderLocation) {
      fromParams += `&from[lnglat]=${props.riderLocation.longitude},${props.riderLocation.latitude}`
    }
    
    const mapUrl = `https://ditu.amap.com/dir?` +
      `${fromParams}&` +
      `to[name]=${encodeURIComponent(destAddress)}&` +
      `to[lnglat]=${destLng},${destLat}&` +
      `via[0][name]=${encodeURIComponent(pickupAddress)}&` +
      `via[0][lnglat]=${pickupLng},${pickupLat}&` +
      `type=car&policy=1`
    
    console.log('高德网页版导航URL:', mapUrl)
    
    window.open(mapUrl, '_blank')
    ElMessage.success(`启动完整导航：${riderAddress} → ${pickupAddress} → ${destAddress}`)
  } catch (error) {
    // 方案2：如果途径点导航失败，提供分段导航
    console.error('途径点导航失败:', error)
    ElMessage.warning('途径点导航暂不可用，为您提供分段导航')
    
    // 先导航到取餐点
    const pickupUrl = `https://ditu.amap.com/dir?to[name]=${encodeURIComponent(pickupAddress)}&to[lnglat]=${pickupLng},${pickupLat}&type=car`
    console.log('分段导航URL（取餐）:', pickupUrl)
    
    window.open(pickupUrl, '_blank')
    
    // 提示用户第二段路径
    setTimeout(() => {
      ElMessage({
        message: `取餐完成后，点击导航到配送地址：${destAddress}`,
        type: 'info',
        duration: 8000,
        showClose: true
      })
    }, 2000)
  }
}

// 导航到取餐地址
const navigateToPickup = async () => {
  if (!props.order?.pickup_coordinates) {
    ElMessage.warning('商家地址坐标不可用')
    return
  }

  try {
    const [lat, lng] = props.order.pickup_coordinates.split(',').map(Number)
    const pickupAddress = props.order.pickupAddress || props.order.storeAddress || '商家地址'
    
    // 获取骑手当前位置的地址
    let riderAddress = '我的位置'
    if (props.riderLocation) {
      try {
        riderAddress = await reverseGeocode(props.riderLocation.latitude, props.riderLocation.longitude)
      } catch (error) {
        console.warn('逆地理编码失败，使用默认起点名称:', error)
        riderAddress = '当前位置'
      }
    }
    
    console.log('取餐导航信息:', {
      rider: { lat: props.riderLocation?.latitude, lng: props.riderLocation?.longitude, address: riderAddress },
      pickup: { lat, lng, address: pickupAddress }
    })
    
    // 移动端和桌面端处理
    if (/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
      // APP导航URL
      const amapUrl = `androidamap://route?sourceApplication=外卖骑手&dlat=${lat}&dlon=${lng}&dname=${encodeURIComponent(pickupAddress)}`
      console.log('APP取餐导航URL:', amapUrl)
      window.location.href = amapUrl
    } else {
      // 网页版导航，包含完整的起点和终点信息
      let fromParams = `from[name]=${encodeURIComponent(riderAddress)}`
      if (props.riderLocation) {
        fromParams += `&from[lnglat]=${props.riderLocation.longitude},${props.riderLocation.latitude}`
      }
      
      const webUrl = `https://ditu.amap.com/dir?${fromParams}&to[name]=${encodeURIComponent(pickupAddress)}&to[lnglat]=${lng},${lat}&type=car&policy=1`
      console.log('网页版取餐导航URL:', webUrl)
      window.open(webUrl, '_blank')
    }
    
    ElMessage.success(`正在导航：${riderAddress} → ${pickupAddress}`)
  } catch (error) {
    console.error('导航到取餐地址失败:', error)
    ElMessage.error('导航启动失败')
  }
}

// 导航到配送地址
const navigateToDestination = async () => {
  if (!props.order?.delivery_coordinates) {
    ElMessage.warning('配送地址坐标不可用')
    return
  }

  try {
    const [lat, lng] = props.order.delivery_coordinates.split(',').map(Number)
    const deliveryAddress = props.order.delivery_address || props.order.address || '配送地址'
    
    // 获取骑手当前位置的地址
    let riderAddress = '我的位置'
    if (props.riderLocation) {
      try {
        riderAddress = await reverseGeocode(props.riderLocation.latitude, props.riderLocation.longitude)
      } catch (error) {
        console.warn('逆地理编码失败，使用默认起点名称:', error)
        riderAddress = '当前位置'
      }
    }
    
    console.log('直达导航信息:', {
      rider: { lat: props.riderLocation?.latitude, lng: props.riderLocation?.longitude, address: riderAddress },
      destination: { lat, lng, address: deliveryAddress }
    })
    
    // 移动端和桌面端处理
    if (/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
      // APP导航URL，包含起点信息
      const amapUrl = `androidamap://route?sourceApplication=外卖骑手&dlat=${lat}&dlon=${lng}&dname=${encodeURIComponent(deliveryAddress)}`
      console.log('APP直达导航URL:', amapUrl)
      window.location.href = amapUrl
    } else {
      // 网页版导航，包含完整的起点和终点信息
      let fromParams = `from[name]=${encodeURIComponent(riderAddress)}`
      if (props.riderLocation) {
        fromParams += `&from[lnglat]=${props.riderLocation.longitude},${props.riderLocation.latitude}`
      }
      
      const webUrl = `https://ditu.amap.com/dir?${fromParams}&to[name]=${encodeURIComponent(deliveryAddress)}&to[lnglat]=${lng},${lat}&type=car&policy=1`
      console.log('网页版直达导航URL:', webUrl)
      window.open(webUrl, '_blank')
    }
    
    ElMessage.success(`正在导航：${riderAddress} → ${deliveryAddress}`)
  } catch (error) {
    console.error('导航到配送地址失败:', error)
    ElMessage.error('导航启动失败')
  }
}

// 更新骑手位置
const updateLocation = async () => {
  locationUpdating.value = true
  
  try {
    // 获取当前位置
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const newLocation = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude
          }
          
          // 重新计算距离（模拟）
          distance.value = Math.random() * 5 + 1
          estimatedTime.value = Math.ceil(distance.value * 3)
          
          // 触发位置更新事件
          emit('locationUpdate', newLocation)
          
          ElMessage.success('位置更新成功')
          locationUpdating.value = false
        },
        (error) => {
          console.error('获取位置失败:', error)
          ElMessage.error('获取位置失败，请检查定位权限')
          locationUpdating.value = false
        },
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 60000
        }
      )
    } else {
      ElMessage.error('浏览器不支持定位功能')
      locationUpdating.value = false
    }
  } catch (error) {
    console.error('位置更新失败:', error)
    ElMessage.error('位置更新失败')
    locationUpdating.value = false
  }
}

// 关闭地图
const handleClose = async () => {
  try {
    // 先清理地图资源
    destroyMap()
    // 等待一个微任务确保清理完成
    await new Promise(resolve => setTimeout(resolve, 0))
    // 再关闭弹窗
    emit('close')
  } catch (error) {
    console.error('关闭地图时出错:', error)
    // 确保弹窗还是能关闭
    emit('close')
  }
}

// 销毁地图
const destroyMap = () => {
  try {
    // 重置加载状态
    mapLoading.value = true
    
    // 清理地图标记
    try {
      if (riderMarker) {
        riderMarker.setMap && riderMarker.setMap(null)
        riderMarker = null
      }
    } catch (e) {
      console.warn('清理骑手标记失败:', e)
    }
    
    try {
      if (destinationMarker) {
        destinationMarker.setMap && destinationMarker.setMap(null)
        destinationMarker = null
      }
    } catch (e) {
      console.warn('清理目标标记失败:', e)
    }
    
    try {
      if (pickupMarker) {
        pickupMarker.setMap && pickupMarker.setMap(null)
        pickupMarker = null
      }
    } catch (e) {
      console.warn('清理取餐标记失败:', e)
    }
    
    try {
      if (routeLine) {
        routeLine.setMap && routeLine.setMap(null)
        routeLine = null
      }
    } catch (e) {
      console.warn('清理路线失败:', e)
    }
    
    // 销毁地图实例
    try {
      if (map) {
        map.destroy && map.destroy()
        map = null
      }
    } catch (e) {
      console.warn('销毁地图实例失败:', e)
      map = null // 强制设为null
    }
    
    // 清理DOM容器
    try {
      const domElement = document.getElementById(mapId.value)
      if (domElement) {
        domElement.innerHTML = ''
      }
      if (mapContainer.value) {
        mapContainer.value.innerHTML = ''
      }
    } catch (e) {
      console.warn('清理DOM容器失败:', e)
    }
    
    // 重置状态
    distance.value = 0
    estimatedTime.value = 0
    
  } catch (error) {
    console.warn('地图清理过程中出现错误:', error)
  }
}

// 组件卸载时清理资源
onUnmounted(() => {
  destroyMap()
})
</script>

<style scoped>
.delivery-map-dialog {
  :deep(.el-dialog) {
    margin-top: 5vh;
    max-height: 90vh;
    overflow: hidden;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
    overflow-y: auto; /* 改为可滚动 */
    max-height: calc(90vh - 140px); /* 稍微增加可用空间 */
    box-sizing: border-box;
  }

  :deep(.el-dialog__footer) {
    padding: 15px 20px;
    flex-shrink: 0;
  }

  .map-container {
    height: 70vh; /* 恢复固定高度 */
    min-height: 500px; /* 确保最小高度 */
    max-height: calc(90vh - 160px); /* 减去标题栏、内边距和底部按钮的高度 */
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }

  .map-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 16px;
    flex-shrink: 0; /* 防止被压缩 */
    max-height: 150px; /* 限制最大高度 */
    overflow: hidden;

    .order-info {
      flex: 1;

      h3 {
        margin: 0 0 12px 0;
        color: #333;
        font-size: 18px;
      }

      .location-item {
        margin: 8px 0;
        color: #666;
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 0;
        border-bottom: 1px solid #e9ecef;

        .location-label {
          font-weight: 500;
          color: #333;
          min-width: 40px;
        }
      }

      .location-item:last-child {
        border-bottom: none;
      }

      .pickup-location {
        color: #52c41a;
      }

      .delivery-location {
        color: #f5222d;
      }

      p {
        margin: 4px 0;
        color: #666;
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }

    .distance-info {
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-items: flex-end;

      .eta-tag {
        min-width: 80px;
        text-align: center;
      }

      .route-description {
        margin-top: 4px;
        font-size: 12px;
        opacity: 0.8;
      }
    }
  }

  .map-area {
    flex: 1;
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    background: #f0f0f0;
    min-height: 300px; /* 确保地图有最小显示高度 */
    max-height: 100%; /* 不超过父容器 */

    .map-loading {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      color: #666;

      .el-icon {
        font-size: 32px;
        margin-bottom: 8px;
      }
    }
  }

  .map-actions {
    display: flex;
    gap: 12px;
    padding: 16px 0;
    justify-content: center;
    flex-wrap: wrap;

    .el-button {
      flex: 1;
      min-width: 100px;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    flex-shrink: 0; /* 防止底部按钮被压缩 */
    padding: 15px 20px;
    box-sizing: border-box;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .delivery-map-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 2vh auto !important;
      max-height: none !important; /* 移除高度限制 */
      height: auto !important; /* 自动高度 */
      overflow: visible; /* 允许溢出 */
    }

    :deep(.el-dialog__body) {
      padding: 15px;
      max-height: none !important; /* 移除高度限制 */
      height: auto !important; /* 自动高度 */
      overflow: visible; /* 改为可见，不强制滚动 */
    }

    :deep(.el-dialog__footer) {
      padding: 10px 15px;
    }

    .map-container {
      height: auto !important; /* 改为自动高度 */
      min-height: auto; /* 移除最小高度限制 */
      max-height: none !important; /* 移除最大高度限制 */
      overflow: visible; /* 允许溢出 */
      display: flex;
      flex-direction: column;
      gap: 16px; /* 添加组件间距 */
    }

    .map-header {
      flex-direction: column;
      gap: 12px;
      padding: 16px;
      margin-bottom: 0; /* 移除margin，使用gap代替 */
      max-height: none !important; /* 移除高度限制 */
      height: auto; /* 自动高度 */
      flex-shrink: 0; /* 防止被压缩 */

      .order-info {
        .location-item {
          padding: 10px 0;
          
          span {
            word-break: break-all; /* 长文本换行 */
            line-height: 1.4;
          }
        }
      }

      .distance-info {
        align-items: flex-start;
        flex-direction: row;
        flex-wrap: wrap;
        gap: 8px;
        width: 100%;
        justify-content: flex-start;
      }
    }

    .map-area {
      height: 400px !important; /* 固定合适的地图高度 */
      min-height: 400px;
      max-height: none;
      flex-shrink: 0; /* 防止被压缩 */
      width: 100%;
      border-radius: 8px;
      overflow: hidden;
    }

    .map-actions {
      padding: 16px 0 0 0; /* 只保留顶部padding */
      flex-shrink: 0; /* 防止被压缩 */
      
      .el-button {
        flex: 1;
        min-width: 80px;
        font-size: 12px;
        padding: 8px 12px;
      }
    }
  }
}

/* 深色主题适配 */
@media (prefers-color-scheme: dark) {
  .delivery-map-dialog {
    .map-header {
      background: #2a2a2a;
      color: #fff;

      .order-info {
        h3 {
          color: #fff;
        }

        p {
          color: #ccc;
        }
      }
    }

    .map-area {
      background: #1a1a1a;
    }
  }
}

/* 简单地图样式 */
.simple-map {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-align: center;
  padding: 20px;
  border-radius: 8px;

  .map-info {
    width: 100%;
    max-width: 500px;

    h3 {
      margin-bottom: 20px;
      font-size: 24px;
      color: white;
    }

    .location-items {
      display: flex;
      flex-direction: column;
      gap: 20px;
      margin-bottom: 20px;

      .location-item {
        display: flex;
        align-items: center;
        gap: 15px;
        padding: 15px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
        backdrop-filter: blur(10px);

        .marker-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          color: white;
          font-weight: bold;

          &.rider-marker {
            background: #1890ff;
          }

          &.destination-marker {
            background: #f5222d;
          }
        }

        .location-details {
          flex: 1;
          text-align: left;

          p {
            margin: 2px 0;
            
            &:first-child {
              font-weight: bold;
              font-size: 16px;
            }
          }
        }
      }
    }

    .map-note {
      padding: 10px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 8px;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.8);
    }
  }
}

/* 简单地图的响应式 */
@media (max-width: 768px) {
  .simple-map {
    padding: 15px;

    .map-info {
      h3 {
        font-size: 20px;
      }

      .location-items {
        .location-item {
          flex-direction: column;
          text-align: center;

          .location-details {
            text-align: center;
          }
        }
      }
    }
  }
}
</style>
